package com.thread.Concurrent;

public class Synchronized {
    public static void main(String[] args) {
        GetTicket getTicket = new GetTicket();
        new Thread(getTicket,"刘备").start();
        new Thread(getTicket,"孙权").start();
        new Thread(getTicket,"曹操").start();

    }
}
//买票
class GetTicket implements Runnable{
    int ticket = 10;
    boolean flag = true;
    @Override
    public void run() {
        while (flag){
            try {
                buy();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
    //synchronized:同步方法，锁的是this
    private synchronized void buy() throws InterruptedException {
        if(ticket<1){
            flag =false;
            return;
        }

        Thread.sleep(100);

        System.out.println(Thread.currentThread().getName()+"买到了票"+ticket--);
    }
}